
# $Id: Utils.pm 96 2013-03-25 07:47:45Z chengxin.cai $

package Provision::Utils;

use strict;
use base 'Exporter';

use POSIX;
use Term::ANSIColor qw(:constants);

use config ':all';
use instance ':all';

our @EXPORT_OK = qw(
    stopInstance
    removeAllInstances
    performStep 
);

sub stopInstance {
    my ($squser, $test) = @_;

    my @nodes = get_user_sql_nodes($squser);

    my $sq_home = runCmd2( "su - $squser -c 'echo \$SQ_HOME'" );

    logDebug("SQ_HOME for $squser is $sq_home");

    if ( $sq_home =~ qq{/opt/hp} ) {
        my $cmd = "su - $squser -c 'ssh $nodes[0] sqstopall'";
        return runCmdNoCheck($cmd, $test);
    }

    return 0;

}

sub removeAllInstances {
    my ($squser, $test) = @_;

    my @image_names = get_image_names();

    my @instances;
    for my $image (@image_names) {
        my @dirs = glob "/cm/images/$image/opt/hp/$squser/*";
        map { s/\/cm\/images\/$image//; } @dirs;
        push @instances, @dirs;
    }

    # remove duplicats
    @instances  = keys %{{ map { $_ => 1 } @instances }};

    if ( @instances > 0 ) {
        my $cmd = "$nvpath/bin/remoldinstance -l " . join(',', @instances);

        return runCmdNoCheck( "su $squser -c '$cmd'", $test );
    }

    return 0;
}

### running one step for provisioning or undo
### Argument:  3 arguments
###     $_[0]: one provosioning object, can be a Provision::User
###     $_[1]: one provisioning step, must have title, cmd or code
###     $_[2]: a flag to show whether for test mode
sub performStep {
    my ($pobj, $step, $test) = @_;

    print "$step->{title} for " . $pobj->id();
    if ( $ENV{INST_PROV_DEBUG} ) {
        print ",\t\tPress ENTER to continue (Q/q to quit)...";
        my $ans = <>;
        if ($ans =~ /^q$/i) { exit(config::UNKNOWN); }
    }
    else { print "\n";}

    my $ret;
    if ( defined $step->{code} ) {
        $ret = &{ $step->{code} }($pobj->id(), $test);
        print makeFixedString($step->{title}, '.');
    }
    else {
        my $cmd = $step->{cmd};
        $cmd .= " $step->{args}" if ($step->{args});
        $cmd .= " " . $pobj->get_idarg();

        $ret = runCmdNoCheck($cmd, $test);
        print makeFixedString($cmd, '.');
    }

    if ($ret == 0) {
        print GREEN . "[PASSED]" . RESET . "\n";
    }
    else {
        print RED . "[FAILED]" . RESET . "\n";
        logError( "$step->{title} for " . $pobj->id() );
    }

    return $ret;
}

1;

